package com.dorje.sys.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dorje.sys.bean.Constants;
import com.dorje.sys.entity.User;

@Controller
@RequestMapping("/login/")
public class LoginController {
	
	@Resource
	private CacheManager shiroCacheManager;
	private final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	
	@RequestMapping(value="login",method={RequestMethod.POST,RequestMethod.GET})
	public String login(HttpServletRequest request, HttpServletResponse response) throws IOException{
		Subject user = SecurityUtils.getSubject();
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		System.out.println(password);
		System.out.println(DigestUtils.sha1Hex(password));
		UsernamePasswordToken token = new UsernamePasswordToken(account,DigestUtils.sha1Hex(password));
		String msg = "";
		try {
			user.login(token);
		}catch(UnknownAccountException uae){
			msg = "账号不存在";
		}catch (IncorrectCredentialsException ice){
			msg = "密码错误";
		}	catch (LockedAccountException lae) {
			msg = "账号被锁定";
		}catch(AuthenticationException e){
			msg = "认证错误";
		}catch (Exception e) {
			msg = "登陆失败";
		}		
		response.setContentType("text/html;charset=utf-8");
		System.out.println(msg);
		response.getWriter().write(msg);
		return "redirect:/admin/index";
		
	}
	
	@RequestMapping("logout")
	public String logout(HttpServletResponse response){
		Subject subject = SecurityUtils.getSubject();
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		if(user != null){
			Cookie cookie = new Cookie(user.getAccount(), null);
			cookie.setMaxAge(0);// 如果参数是0，就说明立即删除
			response.addCookie(cookie);
		}
		if(subject != null) {
			subject.logout();
		}		
		shiroCacheManager.getCache(Constants.authenticationCacheName).clear();
		return "redirect:/login.jsp";
	}
	
}
